const { createApp, ref, onMounted, reactive } = Vue;

// API基础URL
const API_BASE_URL = 'http://localhost:8080/api';

// 创建Vue应用
const app = createApp({
    setup() {
        // 状态管理
        const state = reactive({
            messages: [],
            newMessage: '',
            conversations: [],
            selectedConversationId: null,
            isLoading: false,
            showWelcome: true,
            userId: 1, // 默认用户ID，实际项目中应从登录状态获取
            shortcutQuestions: [
                { title: '解释量子计算', description: '用简单的语言解释' },
                { title: '写一篇短文', description: '关于环境保护的重要性' },
                { title: '代码调试', description: '帮我看看这段Java代码' },
                { title: '旅行建议', description: '北京三日游攻略' }
            ]
        });

        // 获取对话列表
        const fetchConversations = async () => {
            try {
                const response = await axios.get(`${API_BASE_URL}/conversations?userId=${state.userId}`);
                if (response.data.success) {
                    state.conversations = response.data.data;
                    // 如果有对话，默认选中第一个
                    if (state.conversations.length > 0 && !state.selectedConversationId) {
                        selectConversation(state.conversations[0].id);
                    }
                }
            } catch (error) {
                console.error('获取对话列表失败:', error);
            }
        };

        // 获取特定对话的消息
        const fetchMessages = async (conversationId) => {
            try {
                state.isLoading = true;
                const response = await axios.get(`${API_BASE_URL}/messages?conversationId=${conversationId}&userId=${state.userId}`);
                if (response.data.success) {
                    state.messages = response.data.data;
                    state.showWelcome = false;
                    // 滚动到底部
                    scrollToBottom();
                }
            } catch (error) {
                console.error('获取消息失败:', error);
            } finally {
                state.isLoading = false;
            }
        };

        // 选择对话
        const selectConversation = (conversationId) => {
            state.selectedConversationId = conversationId;
            fetchMessages(conversationId);
        };

        // 创建新对话
        const createNewConversation = async () => {
            try {
                const response = await axios.post(`${API_BASE_URL}/conversations`, null, {
                    params: { userId: state.userId, title: '新对话' }
                });
                if (response.data.success) {
                    const newConversation = response.data.data;
                    state.conversations.unshift(newConversation);
                    selectConversation(newConversation.id);
                }
            } catch (error) {
                console.error('创建新对话失败:', error);
            }
        };

        // 发送消息
        const sendMessage = async () => {
            if (!state.newMessage.trim() || !state.selectedConversationId || state.isLoading) return;

            const messageContent = state.newMessage.trim();
            // 添加用户消息到界面
            const userMessage = {
                id: Date.now(),
                content: messageContent,
                role: 'user',
                createTime: new Date().toISOString()
            };
            state.messages.push(userMessage);
            state.newMessage = '';
            state.showWelcome = false;
            scrollToBottom();

            try {
                state.isLoading = true;
                // 调用API发送消息
                const response = await axios.post(`${API_BASE_URL}/messages`, null, {
                    params: {
                        conversationId: state.selectedConversationId,
                        userId: state.userId,
                        content: messageContent
                    }
                });

                if (response.data.success) {
                    // 添加AI回复到界面
                    const aiMessage = response.data.data.aiMessage;
                    state.messages.push(aiMessage);
                    scrollToBottom();
                    // 更新对话列表中的最后一条消息
                    updateConversationLastMessage(state.selectedConversationId, messageContent);
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                // 显示错误消息
                state.messages.push({
                    id: Date.now() + 1,
                    content: '发送消息失败，请重试',
                    role: 'assistant',
                    createTime: new Date().toISOString()
                });
            } finally {
                state.isLoading = false;
                scrollToBottom();
            }
        };

        // 更新对话列表中的最后一条消息
        const updateConversationLastMessage = (conversationId, content) => {
            const conversation = state.conversations.find(c => c.id === conversationId);
            if (conversation) {
                // 更新对话标题为第一条消息内容（如果是新对话）
                if (conversation.title === '新对话' && content.length > 0) {
                    conversation.title = content.length > 20 ? content.substring(0, 20) + '...' : content;
                    // 调用API更新对话标题
                    axios.put(`${API_BASE_URL}/conversations/${conversationId}/title`, null, {
                        params: { userId: state.userId, title: conversation.title }
                    }).catch(error => {
                        console.error('更新对话标题失败:', error);
                    });
                }
                conversation.updateTime = new Date().toISOString();
                // 将当前对话移到列表顶部
                const index = state.conversations.findIndex(c => c.id === conversationId);
                if (index > -1) {
                    const [removed] = state.conversations.splice(index, 1);
                    state.conversations.unshift(removed);
                }
            }
        };

        // 使用快捷问题
        const useShortcutQuestion = (question) => {
            if (!state.selectedConversationId) {
                // 如果没有选中的对话，先创建新对话
                createNewConversation().then(() => {
                    state.newMessage = question.title;
                    sendMessage();
                });
            } else {
                state.newMessage = question.title;
                sendMessage();
            }
        };

        // 滚动到消息底部
        const scrollToBottom = () => {
            setTimeout(() => {
                const chatMessages = document.getElementById('chatMessages');
                if (chatMessages) {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            }, 100);
        };

        // 键盘事件处理
        const handleKeyDown = (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        };

        // 初始化
        onMounted(() => {
            // 监听输入框键盘事件
            document.getElementById('messageInput')?.addEventListener('keydown', handleKeyDown);
            // 监听新对话按钮点击
            document.getElementById('newChatBtn')?.addEventListener('click', createNewConversation);
            // 监听发送按钮点击
            document.getElementById('sendButton')?.addEventListener('click', sendMessage);
            // 获取对话列表
            fetchConversations();
        });

        return {
            ...state,
            selectConversation,
            createNewConversation,
            sendMessage,
            useShortcutQuestion,
            handleKeyDown
        };
    }
});

// 挂载应用
app.mount('#app');

// 添加Axios到window对象（实际项目中建议通过npm安装）
window.axios = {
    get: async (url) => {
        const response = await fetch(url);
        return response.json();
    },
    post: async (url, data, config) => {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: data ? JSON.stringify(data) : null,
            ...config
        });
        return response.json();
    },
    put: async (url, data, config) => {
        const response = await fetch(url, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: data ? JSON.stringify(data) : null,
            ...config
        });
        return response.json();
    }
};